﻿using System;
using System.Collections.Generic;
using System.Reflection;
using AllInOnePluginBL.Helpers;
using AllInOnePluginBL.SiteScrappers;
using NLog;

namespace AllInOnePluginBL.jobs
{
    /// <summary>
    /// Summary description for BaseScrapperJob
    /// </summary>
    public abstract class BaseScrapperJob : IJob
    {
        #region Protected Members
        protected readonly Logger _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);
        protected readonly List<ISiteScapper> _siteScappers = new List<ISiteScapper>();
        protected readonly PluginDBHandler _pluginDBHandler = PluginDBHandler.Instance;
        protected readonly JobType _jobType = JobType.None;
        protected readonly long _jobTypeId; 
        #endregion

        protected BaseScrapperJob(int runTimeIntervalInHours, JobType jobType)
        {
            _jobType = jobType;
            if (_jobType == JobType.None) throw new Exception("JobType is not valid");

            var jobTypeItem = _pluginDBHandler.GetJobType(_jobType.ToString()) ??
                          _pluginDBHandler.CreateJobType(_jobType.ToString(), runTimeIntervalInHours);

            _jobTypeId = jobTypeItem.JobTypeID;
        }

        #region Implementation of IJob
        public virtual void Execute()
        {
            throw new NotImplementedException();
        }
        #endregion

        #region Protected Methods
        protected void UpdateMainJobRunTime()
        {
            try
            {
                var pluginDBHandler = PluginDBHandler.Instance;
                pluginDBHandler.UpdateJobTypeRunTime(_jobTypeId, DateTime.Now);
            }
            catch (Exception ex)
            {
                _log.ErrorException("Error UpdateMainJobRunTime: SitesScrapperJob", ex);
            }
        }

        protected void UpdateSiteScapperJobRunTime(ISiteScapper siteScapper)
        {
            try
            {
                var pluginDBHandler = PluginDBHandler.Instance;
                pluginDBHandler.UpdateJobRunTime(siteScapper.JobID, DateTime.Now);
            }
            catch (Exception ex)
            {
                _log.ErrorException(string.Format("Error UpdateSiteScapperJobRunTime: {0}", siteScapper.Name), ex);
            }
        } 
        #endregion
    }
}